# -*- coding: utf-8 -*-
import base64
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.tz import local_now

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    'QR6865': {  # dwc 10-3000
        'API_KEY': '6zpypKVEIDN4XZxw7wFogzByQJcRLPft',
        'gateway': 'http://t1zhifu.com/pay/order',
        'query_gateway': 'http://t1zhifu.com/pay/order/query',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    s = s.decode('utf-8')
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = _gen_sign(base64.b64decode(params['context']) + key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("wopay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


# jfwx
# jfali
def _get_pay_type(service):
    if service == 'wxpay':
        payType = 'jfwx'
    else:
        payType = 'jfali'
    return payType


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('merchNo', app_id),
        ('orderNo', str(pay.id)),
        ('amount', str(pay_amount)),
        ('currency', 'CNY'),
        ('outChannel', _get_pay_type(service)),
        ('bankCode', '123123'),
        ('title', 'charge'),
        ('product', 'charge'),
        ('memo', 'charge'),
        ('returnUrl', '{}/pay/api/{}/wopay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, str(pay.id))),
        ('notifyUrl', '{}/pay/api/{}/wopay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('reqTime', local_now().strftime('%Y%m%d%H%M%S')),
        ('userId', str(pay.user_id)),
    ))
    j = json.dumps(parameter_dict, separators=(',', ':'))
    sign = _gen_sign(j + api_key)
    b = base64.b64encode(j)
    d = {'sign': sign, 'context': b, 'encryptType': 'MD5'}
    url = _get_gateway(app_id)
    _LOGGER.info("wopay create: %s ,%s, %s", j, d, url)
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(url, data=json.dumps(d, separators=(',', ':')), headers=headers, timeout=5)
    _LOGGER.info("wopay create rsp: %s", response.text)
    r = json.loads(response.text)
    if str(r['code']) != '0':
        raise ParamError('wopay pay_id: %s create error ' % pay.id)
    context = json.loads(base64.b64decode(r['context']))
    return {'charge_info': context['qrcode_url']}


# '''{'result':'ok'}'''
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    _LOGGER.info("wopay notify body: %s", request.body)
    data = json.loads(request.body)
    verify_notify_sign(data, api_key)
    data = json.loads(base64.b64decode(data['context']))
    pay_id = data['orderNo']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('wopay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['orderState'])
    trade_no = data['businessNo']
    total_fee = float(data['amount'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == '1':
        _LOGGER.info('wopay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('merchNo', app_id),
        ('orderNo', str(pay_order.id)),
    ))
    j = json.dumps(parameter_dict, separators=(',', ':'))
    sign = _gen_sign(j + api_key)
    b = base64.b64encode(j)
    d = {'sign': sign, 'context': b, 'encryptType': 'MD5'}
    _LOGGER.info("wopay query: %s", d)
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_get_query_gateway(app_id), data=json.dumps(d, separators=(',', ':')), headers=headers,
                             timeout=5)
    _LOGGER.info("wopay query rsp: %s", response.text)
    r = json.loads(response.text)
    if str(r['code']) != '0':
        return
    if response.status_code == 200:
        data = json.loads(base64.b64decode(r['context']))
        mch_id = pay_order.mch_id
        trade_status = str(data['orderState'])
        total_fee = float(data['amount'])
        trade_no = data['businessNo']

        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }

        # 待支付 - 下单成功0
        # 支付成功1
        # 支付失败2
        # 处理中3
        # 关闭4
        if trade_status == '1':
            _LOGGER.info('wopay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)
